#ifndef REMOTECALLTHREAD_H
#define REMOTECALLTHREAD_H

#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include "remotecall.h"
inline static int fps=1000/100;
inline std::mutex m_dataMutex;
inline static QString m_receivedData;
class RemoteCallThread
{
public:
    explicit RemoteCallThread()
        : m_running(false) {}

    ~RemoteCallThread() {
        stop();
    }

    void start() {
        if (m_running) return;
        m_running = true;
        m_thread = std::thread(&RemoteCallThread::run, this);
    }

    void stop() {
        if (!m_running) return;
        m_running = false;
        m_cv.notify_one(); // 唤醒可能正在等待的线程
        if (m_thread.joinable()) {
            m_thread.join();
        }
    }

    void setSize(int w, int h) {
        std::lock_guard<std::mutex> lock(m_sizeMutex);
        m_width = w;
        m_height = h;
    }

    QString getData() {
        std::lock_guard<std::mutex> lock(m_dataMutex);
        return m_receivedData;
    }

private:
    void run() {
        // 每个线程有自己的 RemoteCall 实例
        RemoteCall remoteCall;
        remoteCall.run(); // 初始化远程调用
        // int threadFrameCount = 0;
        // auto lastTime = std::chrono::steady_clock::now();
        while (m_running) {
            // 执行远程调用
            QString data = remoteCall.Call_fun_rect(m_width, m_height);

            // 更新共享数据
            if (!data.isEmpty()) {
                std::lock_guard<std::mutex> lock(m_dataMutex);
                m_receivedData = data;
            }

            // 线程帧率统计
            // threadFrameCount++;
            // auto now = std::chrono::steady_clock::now();
            // auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastTime).count();

            // if (elapsed >= 1000) {
            //     qDebug() << "RemoteCallThread FPS:" << threadFrameCount;
            //     threadFrameCount = 0;
            //     lastTime = now;
            // }

            // 控制刷新频率 (FPS)
            std::unique_lock<std::mutex> lock(m_cvMutex);
            m_cv.wait_for(lock, std::chrono::milliseconds(fps), [this] {
                return !m_running; // 如果停止标志被设置，立即唤醒
            });
        }
    }

    std::atomic<bool> m_running;
    std::thread m_thread;

    // 尺寸同步
    std::mutex m_sizeMutex;
    int m_width = 0;
    int m_height = 0;

    // 线程控制
    std::mutex m_cvMutex;
    std::condition_variable m_cv;
};

#endif // REMOTECALLTHREAD_H
